import numpy as np
import math
import scipy.stats as stats
from sklearn.datasets import make_sparse_coded_signal

# 一般来说，

# PSNR高于40dB说明图像质量极好（即非常接近原始图像），
# 在30—40dB通常表示图像质量是好的（即失真可以察觉但可以接受），
# 在20—30dB说明图像质量差；
# 最后，PSNR低于20dB图像不可接受

def psnr(target, ref):
    # target:目标图像  ref:参考图像  scale:尺寸大小
    # assume RGB image
    target_data = np.array(target)/255
    # target_data = target_data[scale:-scale,scale:-scale]
 
    ref_data = np.array(ref)/255
    # ref_data = ref_data[scale:-scale,scale:-scale]
 
    diff = ref_data - target_data
    # https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html
    diff = diff.flatten('C')
    mse = np.mean(diff ** 2.)
    rmse = math.sqrt(mse)
    if mse < 1e-10:
        return 100, rmse
    return 20*math.log10(1.0/rmse), rmse


def snr_1d(target, ref):
    # target:1D信号  denoise_signal
    # ref:1D信号  resdual_signal
    target_data = np.array(target)
 
    ref_data = np.array(ref)
    avg = np.average(target_data[:3])
    sigmal_std = np.std(ref_data)
    # https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html
    signal_snr = avg/sigmal_std + 1e-6
    return signal_snr



def corr_calc(signal_1, signal_2):
    corr_para, p = stats.pearsonr(signal_1, signal_2) 
    return corr_para


# def pearsonr(x, y):
#     """
#     Calculates a Pearson correlation coefficient and the p-value for testing
#     non-correlation.
#     The Pearson correlation coefficient measures the linear relationship
#     between two datasets. Strictly speaking, Pearson's correlation requires
#     that each dataset be normally distributed. Like other correlation
#     coefficients, this one varies between -1 and +1 with 0 implying no
#     correlation. Correlations of -1 or +1 imply an exact linear
#     relationship. Positive correlations imply that as x increases, so does
#     y. Negative correlations imply that as x increases, y decreases.
#     The p-value roughly indicates the probability of an uncorrelated system
#     producing datasets that have a Pearson correlation at least as extreme
#     as the one computed from these datasets. The p-values are not entirely
#     reliable but are probably reasonable for datasets larger than 500 or so.
#     Parameters
#     ----------
#     x : (N,) array_like
#         Input
#     y : (N,) array_like
#         Input
#     Returns
#     -------
#     (Pearson's correlation coefficient,
#      2-tailed p-value)
#     References
#     ----------
#     http://www.statsoft.com/textbook/glosp.html#Pearson%20Correlation
#     """
#     # x and y should have same length.
#     x = np.asarray(x)
#     y = np.asarray(y)
#     n = len(x)
#     mx = x.mean()
#     my = y.mean()
#     xm, ym = x-mx, y-my
#     r_num = np.add.reduce(xm * ym)
#     r_den = np.sqrt(ss(xm) * ss(ym))
#     r = r_num / r_den

#     # Presumably, if abs(r) > 1, then it is only some small artifact of floating
#     # point arithmetic.
#     r = max(min(r, 1.0), -1.0)
#     df = n-2
#     if abs(r) == 1.0:
#         prob = 0.0
#     else:
#         t_squared = r*r * (df / ((1.0 - r) * (1.0 + r)))
#         prob = betai(0.5*df, 0.5, df / (df + t_squared))
#     return r, prob


# Reference
# https://www.huaweicloud.com/articles/4ede675175a5ce0702308428c11a5846.html
# PSNR的全称为“Peak Signal-to-Noise Ratio”，直译为中文就是峰值信噪比。
# 是一种衡量图像质量的指标，在很多领域都会需要这个指标，比如在超分辨率重建图像的时候，PSNR就是很重要的指标了。
# WIKI解释
# 峰值信噪比（英语：Peak signal-to-noise ratio常缩写为PSNR）是一个表示信号最大可能功率和影响它的精度的破坏性噪声功率的比值的工程术语。由于许多信号都有非常宽的动态范围，峰值信号比常用对数分贝单位来表示。




















# Reference:
# 峰值信噪比计算：https://blog.csdn.net/yuhongbei/article/details/102726655
# 